import { BASE_URL } from "./utils/common";

interface KeywordType {
  id: number;
  keyName: string;
  url: string;
}

export const classifyUrl = (list: KeywordType[]) => {
  const first: string[] = [];
  const second: string[] = [];

  list.forEach((val) => {
    if (val.keyName.indexOf("porn") > -1 || val.url.indexOf("gay") > -1) {
      first.push(val.url + ".*");
    } else {
      second.push(val.url + ".*");
    }
  });

  return [...first, ...second];
};

const LIST_KEY = "LIST_KEY";
type listType = string[];
type onChangeCallback = (newList: listType) => void;
export class BanList {
  list: listType = [];
  public async init(onChange?: onChangeCallback) {
    const result = await chrome.storage.sync.get([LIST_KEY]);
    const data = JSON.parse(result[LIST_KEY] || "[]") as string[];
    this.list = data;

    chrome.storage.onChanged.addListener((changes, namespace) => {
      for (let [key, { oldValue, newValue }] of Object.entries(changes)) {
        if (key !== LIST_KEY) return;
        this.list = JSON.parse(newValue);
        onChange && onChange(this.list);
      }
    });
  }

  public async updateList() {
    return fetch(BASE_URL + "/KeywordApi/getKeywordList")
      .then((data) => data.json())
      .then((data) => {
        // classifyUrl(data.list)
        // (data.data as KeywordType[]).filter(val => val.keyName.indexOf("porn") > -1).map(val=>val.url + ".*")
        // const result = (data.data as KeywordType[]).map(val => val.url + ".*")
        chrome.storage.sync.set({
          [LIST_KEY]: JSON.stringify(classifyUrl(data.list)),
        });
      });
  }
  public getList() {
    return this.list;
  }
  public addToList(url: string) {
    this.list = Array.from(new Set([...this.list, url]));
    const obj = JSON.stringify(this.list);
    chrome.storage.sync.set({ [LIST_KEY]: obj }).then(() => {
      console.log(obj);
    });
  }
  public removeFromList(url: string) {
    this.list = this.list.filter((val) => val !== url);
    const obj = JSON.stringify(this.list);
    chrome.storage.sync.set({ [LIST_KEY]: obj }).then(() => {
      console.log(obj);
    });
  }
}
